package com.example.ISearchBlog.controller;

import com.beust.ah.A;
import com.example.ISearchBlog.common.AjaxResult;
import com.example.ISearchBlog.common.ApplicationVariable;
import com.example.ISearchBlog.common.StringTools;
import com.example.ISearchBlog.common.UserSessionTools;
import com.example.ISearchBlog.entity.ArticleInfo;
import com.example.ISearchBlog.entity.UserInfo;
import com.example.ISearchBlog.entity.vo.ArticleInfoVO;
import com.example.ISearchBlog.service.ArticleService;
import com.example.ISearchBlog.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private SearchService searchService;

    @RequestMapping("/add")
    public AjaxResult add(ArticleInfo articleInfo, HttpServletRequest request) {
        //1.非空校验
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
        !StringUtils.hasLength(articleInfo.getContent()))
            return AjaxResult.fail(-1, "参数异常");
        //2.组装数据，得到uid
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        articleInfo.setUid(userInfo.getId());
        //3.持久化，将结果返回给前端
        int result = articleService.add(articleInfo);
        return AjaxResult.success(result);
    }

    //获取文章的详情信息，但是需要鉴权（判断权限的归属人是否是当前用户）
    @RequestMapping("/getdetailbyid")
    public AjaxResult getDetailByIdAndUid(Integer id, HttpServletRequest request) {
        if (id == null || id <= 0) return AjaxResult.fail(-1, "非法参数");
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        return AjaxResult.success(articleService.getDetailByIdAndUid(id, userInfo.getId()));
    }

    @RequestMapping("/update")
    public AjaxResult update(ArticleInfo articleInfo, HttpServletRequest request) {
        //1.非空校验
        if (null == articleInfo || articleInfo.getId() <= 0 ||
                !StringUtils.hasLength(articleInfo.getTitle()) ||
                !StringUtils.hasLength(articleInfo.getContent()))
            return AjaxResult.fail(-1, "参数有误！");
        //获取登录用户，填充到 articleInfo 对象中（修改时要验证权限）
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        articleInfo.setUid(userInfo.getId());
        articleInfo.setUpdatetime(LocalDateTime.now());
        int result = articleService.update(articleInfo);
        return AjaxResult.success(result);
    }

    @RequestMapping("/getdetail")
    public AjaxResult getDetail(Integer id) {
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数有误");
        ArticleInfoVO articleInfoVO = articleService.getDetail(id);
        return AjaxResult.success(articleInfoVO);
    }

    @RequestMapping("/addrcount")
    public AjaxResult addRCount(Integer id) {
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数有误！");
        int result = articleService.addRCount(id);
        return AjaxResult.success(result);
    }

    @RequestMapping("/getUpvoteCount")
    // 获取文章点赞数量
    public AjaxResult getUpvoteCount(Integer id){
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数有误！");
        Integer getUpvoteCount = articleService.getUpvoteCount(id);
        return AjaxResult.success(getUpvoteCount);
    }

    @RequestMapping("/isUpvote")
    // 获取文章点赞状态
    public AjaxResult upvote(Integer id) {
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数有误！");
        Integer isUpvote = articleService.isUpvote(id);
        return AjaxResult.success(isUpvote);
    }
    @RequestMapping("/addUpvoteCount")
    // 增加文章点赞数量
    public AjaxResult addUpvoteCount(Integer id) {
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数有误！");
        Integer upvoteCount = articleService.addUpvoteCount(id);
        return AjaxResult.success(upvoteCount);
    }

    @RequestMapping("/mylist")
    public AjaxResult myList(HttpServletRequest request) {
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        List<ArticleInfo> list = articleService.getListByUid(userInfo.getId());
        //将文章正文截取成文章摘要
        for (ArticleInfo item : list) {
            String content = StringTools.subLength(item.getContent(),
                    ApplicationVariable.ABSTRACT_MAX_LENGTH);
            //todo: 将content 里面的 markdown 关键字去除掉
            item.setContent(content);
        }
        return AjaxResult.success(list);
    }

    @RequestMapping("/del")
    public AjaxResult del(Integer id,HttpServletRequest request) {
        //此时uid不是前端传递过来的，而是从后端中的session 中拿到的，前端如果能够传递uid是不安全的
        if (id == null || id <= 0) return AjaxResult.fail(-1, "参数有误！");
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        int result = articleService.del(id, userInfo.getId());
        return AjaxResult.success(result);
    }

    //反例（不返回一个 AjaxResult 对象）
//    @RequestMapping("/del")
//    public int del(Integer id,HttpServletRequest request) {
//        //此时uid不是前端传递过来的，而是从后端中的session 中拿到的，前端如果能够传递uid是不安全的
//        if (id == null || id <= 0) return 0;
//        UserInfo userInfo = UserSessionTools.getLoginUser(request);
//        int result = articleService.del(id, userInfo.getId());
//        return result;
//    }

    //url的地址尽量不要使用大小写，如果在Linux服务器中是严格区分大小写的
    @RequestMapping("/getlistbypage")
    public AjaxResult getListByPage(Integer pageSize, Integer pageIndex) {
        if (pageSize == null || pageSize <= 0) {
            pageSize = 2;
        }
        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }
        //分页公式
        int offset = (pageIndex - 1) * pageSize;
        List<ArticleInfo> list = articleService.getListByPage(pageSize, offset);
        //多线程并发循环
        list.stream().parallel().forEach(item -> {
            item.setContent(StringTools.subLength(item.getContent(),
                    ApplicationVariable.ABSTRACT_MAX_LENGTH));
        });
        return AjaxResult.success(list);
    }

    @RequestMapping("/getcount")
    public AjaxResult getCount() {
        return AjaxResult.success(articleService.getCount());
    }

    @RequestMapping("/search")
    public AjaxResult search(String keyword) {
        List<ArticleInfo> articleInfos = searchService.searches(keyword);
        for (ArticleInfo item : articleInfos) {
            String content = StringTools.subLength(item.getContent(),
                    ApplicationVariable.ABSTRACT_MAX_LENGTH);
            //todo: 将content 里面的 markdown 关键字去除掉
            item.setContent(content);
        }
        return AjaxResult.success(articleInfos);
    }
}
